使用库时理解javascript中的promise

时间:2022-10-01 05:01:42

I've been trying to wrap my head around asynchronous programming and the use of promises. To help understand them, I've written some trivial nested code, but have run into a snag.

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

Here's the code: http://pastebin.com/hBtk9vER Make sure you install when library (npm install)

这是代码: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();

My problem is that console.log(string) is undefined, when I was expecting it to be "Hello World" after promiseRead() resolves. Interestingly, when I remove the timeout, it works as expected. Can anybody help explain this, why the promise function is executing it's code before promiseRead() has finished timeout.

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

Much appreciated

非常感激

2 个解决方案

#1


2  

It looks like you need to return your deferred object in promiseRead()

看起来你需要在promiseRead()中返回你的延迟对象

#2


1  

some updates

一些更新

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();

#1


2  

It looks like you need to return your deferred object in promiseRead()

看起来你需要在promiseRead()中返回你的延迟对象

#2


1  

some updates

一些更新

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();