WeChat Mini Programs's problem of passing parameters when obtaining background data

everyone, I am a novice, just started Mini Program development, I want to dynamic binding, so that the background can be changed URL to change the page rotation pictures at any time. I encountered a problem when writing. The following is Mini Program"s JS file. I"ll write it as follows. ImageLink can get the value of res.data.image_url in then (), and print dot 1 can type the correct URL address. But outside then (), imageLink is empty again, and print point 2 also shows undefined, so image can"t get URL.

//
const app = getApp();

Page({
  data: {
    image: ""
  },
  //
  onReady: function () {
    let tableID = 11111
    let recordID = "6be0ad376ef5e65b4967718e"
    var imageLink =""

    let Product =  new wx.BaaS.TableObject(tableID)
    Product.get(recordID).then(res => {
      // success
      imageLink = res.data.image_url
      console.log(imageLink)  //1
    }, err => {
      // err
    })
    console.log(imageLink) //2
    this.setData({
      image: imageLink
    })
  },
})

so I changed it to the following, so that setData (), image can get the URL value normally in then (), and print point 3 can print normally, but print point 4 is null. Why does image get the URL value in then () and become empty on the outside? Are they two different objects? If it is a different object, the dynamically bound tag in WXML should not get URL, so why can the dynamically bound tag in WXML display the picture normally?

//
const app = getApp();

Page({
  data: {
    image: ""
  },
  //
  onReady: function () {
    let tableID = 11111
    let recordID = "6be0ad376ef5e65b4967718e"

    let Product =  new wx.BaaS.TableObject(tableID)
    Product.get(recordID).then(res => {
      // success
      this.setData({
        image: res.data.image_url
      })
      console.log(this.data.image) //3
    }, err => {
      // err
    })
    console.log(this.data.image) //4
  },
})

I am not good at learning skills. Although I recently learned Mini Program development and JavaScript, I do not understand why this is above. I hope some bosses can answer my questions, and I can also know where I missed it. Thank you!


print point 3 and print point 4 are asynchronous. Print point 4 prints first. At that time, you didn't get the data. When print point 3 got the data, it rendered to the page. You can take a look at the running sequence of promise, and refer to this link description

.
Menu