search

Home  >  Q&A  >  body text

javascript - Questions about using promise

function test() {
    return new Promise((resolve, reject)=>{
        resolve(123);
    });
}
test().then((a)=>{
    console.log(a);
}).then(function (b) {
    console.log(b);//这行代码被执行了
});

The first parameter method of then should be that promise is executed when resolved, but console.log(b) is actually executed. Why is this

高洛峰高洛峰2736 days ago408

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-05-19 10:19:46

    An uninvited reply!

    In Promise, .then( func ) 会返回一个新的 Promise 实例,这个实例的结果,是把函数体 func 的结果通过执行 Promise.resolve() 得到的。所以在你的问题里,console.log(a) 没有返回值,相当于 Promise.resolve(null) 得到一个状态为 resolved is a Promise instance, so it will continue to the next step.

    Regarding Promise, I recommend you to read my tutorial: N ways of using Promise. It has a very detailed explanation and can basically answer all questions about Promise.

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:19:46

    .then(parameter 1, parameter 2) Parameter 1 is the success callback function (resolve()), parameter 2 is the failure callback function (reject()), because of the way you write it here, the .then after the second one (the first function), will be executed, and the value of b is printed out as undefined, that’s about it! !

    reply
    0
  • Cancelreply