内部promise

时间:2019-02-22 15:36:55

标签: node.js promise

在以下代码中,在(A)点调用resolve()不会导致对then()的调用的createRequest()子句执行。代码已经到了resolve()调用的地步,我已经通过print语句进行了验证。

const request = require('request');

function createRequest() {
  return new Promise(function(resolve, reject) {

    // Setup request
    // ...

    request(options, function(error, response, body) {
      if(!error && response.statusCode == 201) {

        // If the resolve() is done at this point, the then() clause is executed

        uploadFiles(files)
          .then(handles => {
            console.log('handles: ' + handles); // This is printed

            resolve('ok'); // (A) Then clause in call to createRequest is not called
          })
          .catch(reject(requestObj)); // (B) I didn't have this in my initial post
      }
    });
  });
}

function uploadFiles(files) {
  return new Promise(function(resolve, reject) {
    // Upload files
    // ...

    resolve(handles);
  });
}


createRequest()
  .then(message => console.log(message) /* This never executes */)

[编辑]

我在catch()调用中添加了createRequest()子句,但我惊讶地看到打印了某些内容,这很奇怪,因为正在打印handles:语句。我将(B)更改为以下内容:

.catch(() => reject(requestObj));

我的问题解决了。对then()的调用中的createRequest正在执行。不知道为什么会这样。

1 个答案:

答案 0 :(得分:-1)

这是因为catch()需要一个函数,而不是函数调用。即使未执行catch()子句,NodeJS仍然希望它具有有效的功能。如果不是,则诺言将被NodeJS拒绝。例如:

const request = require('request');

function createRequest() {
  return new Promise(function(resolve, reject) {

    var options = {
        url: 'https://www.google.com'
    };

    request(options, function(error, response, body) {
      if(!error && response.statusCode == 200) {    
        uploadFiles()
          .then(handles => {
            resolve('ok');
          })
          .catch(reject('bad')); // (A)
      }
    });
  });
}

function uploadFiles() {
  return new Promise(function(resolve, reject) {
    resolve([1, 2, 3]);
  });
}


createRequest()
  .then(message => console.log(message))
  .catch(message => console.log(message));

这将导致打印出“不良”字样。如果将(A)替换为.catch(() => reject('bad'));,则打印'ok'。