使用库时了解javascript中的promise

时间:2014-01-16 12:07:01

标签: javascript node.js when-js

我一直试图绕过异步编程和使用promises。为了帮助理解它们,我写了一些简单的嵌套代码,但遇到了麻烦。

以下是代码:http://pastebin.com/hBtk9vER 确保在库(npm install)

时安装
var when = require('when');

function promise() {
  console.log("Promise");
    promiseRead().then(function(string) {
    console.log("Inner promise");
    console.log(string);
    });
}

function promiseRead() {
  console.log("PromiseRead");
  return baz().then(function() {
    console.log("Inner Read");
    var deferred = when.defer();
    setTimeout(function() {
      deferred.resolve("Hello World");
    }, 5000);
  });
}

function baz() {
  console.log("BAZ");
  return when(true); 
}

promise();

我的问题是console.log(string)未定义,我希望在"Hello World"结算后promiseRead()promise。有趣的是,当我删除超时时,它按预期工作。任何人都可以帮忙解释一下,为什么promiseRead()函数在{{1}}完成超时之前执行它的代码。

非常感谢

2 个答案:

答案 0 :(得分:2)

看起来你需要在promiseRead()

中返回你的延迟对象

答案 1 :(得分:1)

一些更新

var when = require('when');

function promise() {
  console.log("Promise");
    promiseRead().then(function(string) {
    console.log("Inner promise");
    console.log(string);
    });
}

function promiseRead() {
  console.log("PromiseRead");
  return baz().then(function() {
    console.log("Inner Read");
    var deferred = when.defer();
    setTimeout(function() {
      deferred.resolve("Hello World");
    }, 5000);
    return deferred.promise;
  });
}

function baz() {
  console.log("BAZ");
  return when(true); 
}

promise();