JavaScript Promises和setTimeout

时间:2016-04-08 03:02:29

标签: javascript es6-promise

我一直在玩Promise,但我无法理解以下代码所发生的事情:

org.neo4j.ogm.model.Result

我希望这会在4.1.1.RELEASE点火后立即输出function a() { return new Promise(function (resolve, reject) { resolve("hi from a!"); }); } function b() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("hi from b!"); }, 5000); }); } function c() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("hi from c!"); }, 1000); }); } a().then(function (resultFromA) { console.log("a() responded with: " + resultFromA); b(); }).then(function (resultFromB) { console.log("b() responded with: " + resultFromB); c(); }).then(function (resultFromC) { console.log("c() responded with: " + resultFromC); }); a() responded with: hi from a!b() responded with: hi from b!。但是,我立即得到以下输出:

  

a()回答:嗨来自!

     

b()回复:undefined

     

c()回复:undefined

我在想c() responded with: hi from c!等待这些承诺,但事实并非如此。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:12)

您需要return b()处理程序中的return c()then

then"取代"第一个承诺,其后续承诺是从其回调中返回

如果您的then回调没有return承诺,则then适用于原始承诺,无论内容/结果如何,都将立即执行之前的then回调。

基本上...

a().then(function () {
  b()
}).then( # This "then" is chained off of a's promise

反过来说:

a().then(function () {
  return b()
}).then( # This "then" is chained off of b's promise

答案 1 :(得分:4)

您需要return promises将它们链接起来:

a().then(function (resultFromA) {
  console.log("a() responded with: " + resultFromA);
  // return b() promise
  return b();
}).then(function (resultFromB) { 
  console.log("b() responded with: " + resultFromB);
  // return c() promise
  return c();
}).then(function (resultFromC) { 
  console.log("c() responded with: " + resultFromC);
});

答案 2 :(得分:4)

你忘了从函数调用返回。 Javascript函数不会隐式返回。

function a() { 
    return new Promise(function (resolve, reject) { 
        resolve("hi from a!");
    });
}

function b() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from b!");
        }, 5000);
    });
}

function c() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from c!");
        }, 1000);
    });
}

a().then(function (resultFromA) {
    console.log("a() responded with: " + resultFromA);
    return b(); // return 
}).then(function (resultFromB) { 
    console.log("b() responded with: " + resultFromB);
    return c(); // return
}).then(function (resultFromC) { 
    console.log("c() responded with: " + resultFromC);
});