Javascript 如何使用承诺在节点中编写同步函数

Javascript 如何使用承诺在节点中编写同步函数,javascript,node.js,promise,synchronous,Javascript,Node.js,Promise,Synchronous,1.如何在Node中同步写入承诺,以便获得所需的输出。我是个新手,如果有任何帮助/建议,我将不胜感激 // This is my core function var compareData = function(userIdArray) { return new Promise(function(resolve, reject) { var missingArray = new Array(); userIdArray.forEach(function(id) {

1.如何在Node中同步写入承诺,以便获得所需的输出。我是个新手,如果有任何帮助/建议,我将不胜感激

// This is my core function

 var compareData = function(userIdArray) {
  return new Promise(function(resolve, reject) {
    var missingArray = new Array();
    userIdArray.forEach(function(id) {
      var options = {
        method: 'POST',
        url: 'http://localhost:6006/test1',
        headers:{
         'content-type': 'application/json' },
          body: { email: id },
          json: true
        };

      request(options, function (error, response, body) {
        missingArray.push(body);
      });
    });
    resolve(missingArray);
  });
}


//I'm calling my function here

compareData(userIdArray)
.then(function(missingArray){
  console.log("The Body is: "+ missingArray);
});

/* I expect the console.log to print the missingArray with data from my POST call, 
but it prints an empty array. Can someone please tell me how to do this synchronously.
I'm pretty new to Node and finding it difficult to understand.*/
与及:

有什么需要进一步解释的吗?

和:


有什么需要进一步解释的吗?

没有库,假设
request
没有返回承诺

var compareData = function(userIdArray) {
    return Promise.all(
        userIdArray.map(function(id) {
            var options = {
                method  : 'POST',
                url     : 'http://localhost:6006/test1',
                headers : { 'content-type': 'application/json' },
                body    : { email: id },
                json    : true
            };

            return new Promise(function(resolve, reject) {
                request(options, function(error, response, body) {
                    if (error) {
                        reject();
                    } else {
                        resolve(body);
                    }
                });
            });
        })
    );
}

compareData(userIdArray).then(function(missingArray) {
    console.log(missingArray);
});

没有库,并且假设
请求
尚未返回承诺

var compareData = function(userIdArray) {
    return Promise.all(
        userIdArray.map(function(id) {
            var options = {
                method  : 'POST',
                url     : 'http://localhost:6006/test1',
                headers : { 'content-type': 'application/json' },
                body    : { email: id },
                json    : true
            };

            return new Promise(function(resolve, reject) {
                request(options, function(error, response, body) {
                    if (error) {
                        reject();
                    } else {
                        resolve(body);
                    }
                });
            });
        })
    );
}

compareData(userIdArray).then(function(missingArray) {
    console.log(missingArray);
});

如果您不想按照@Thomas answer使用外部库,您可以直接使用本机承诺,而且不会太冗长

var compareData = function compareData(userIdArray) {
    return Promise.all(userIdArray.map(function (id) {
        return new Promise(function (resolve, reject) {
            var options = {
                method: 'POST',
                url: 'http://localhost:6006/test1',
                headers: {
                    'content-type': 'application/json'
                },
                body: {
                    email: id
                },
                json: true
            };
            return request(options, function (error, response, body) {
                error ? reject(error) : resolve(body);
            });
        });
    }));
};

compareData(userIdArray)
.then(function (missingArray) {
    console.log("The Body is: " + missingArray);
});
或者,由于这是节点,可以处理更现代的代码:

var compareData = userIdArray => 
    Promise.all(userIdArray.map(id => 
        new Promise((resolve, reject) =>
            request({
                method: 'POST',
                url: 'http://localhost:6006/test1',
                headers: {
                    'content-type': 'application/json'
                },
                body: {
                    email: id
                },
                json: true
            }, (error, response, body) => error ? reject(error) : resolve(body))
        )
    ));

compareData(userIdArray)
.then(missingArray => 
    console.log("The Body is: "+ missingArray)
);

如果您不想按照@Thomas answer使用外部库,您可以直接使用本机承诺,而且不会太冗长

var compareData = function compareData(userIdArray) {
    return Promise.all(userIdArray.map(function (id) {
        return new Promise(function (resolve, reject) {
            var options = {
                method: 'POST',
                url: 'http://localhost:6006/test1',
                headers: {
                    'content-type': 'application/json'
                },
                body: {
                    email: id
                },
                json: true
            };
            return request(options, function (error, response, body) {
                error ? reject(error) : resolve(body);
            });
        });
    }));
};

compareData(userIdArray)
.then(function (missingArray) {
    console.log("The Body is: " + missingArray);
});
或者,由于这是节点,可以处理更现代的代码:

var compareData = userIdArray => 
    Promise.all(userIdArray.map(id => 
        new Promise((resolve, reject) =>
            request({
                method: 'POST',
                url: 'http://localhost:6006/test1',
                headers: {
                    'content-type': 'application/json'
                },
                body: {
                    email: id
                },
                json: true
            }, (error, response, body) => error ? reject(error) : resolve(body))
        )
    ));

compareData(userIdArray)
.then(missingArray => 
    console.log("The Body is: "+ missingArray)
);

根据定义,承诺是异步的,您可以*(do)*同步返回承诺,但承诺值始终是异步解析的。承诺不能是同步的,同步代码通常不需要承诺,所以这没有什么意义?您可以使用承诺中的
missingArray
var立即解析
request
是异步的,因此在解析承诺后将调用push,因此在then函数中使用空数组。你需要的是一个
承诺。所有的
都围绕着对所有用户ID的请求。好的。有道理。你能给我建议一种在Node中编写代码的方法,这样我就可以得到我想要的输出(没有承诺)?使用,和。承诺是异步的,你可以*(做)*同步返回承诺,但承诺的值总是异步解析的。承诺不能是同步的,同步代码通常不需要承诺,所以这没有什么意义?您正在使用承诺中的
missingArray
var立即解决问题
request
是异步的,因此在解析承诺后将调用push,因此在then函数中使用空数组。你需要的是一个
承诺。所有的
都围绕着对所有用户ID的请求。好的。有道理。你能给我建议一种在Node中编写代码的方法,这样我就可以得到我想要的输出(没有承诺)?使用,和。谢谢@Jaromanda X。这很好,但要兑现承诺需要很多时间。我在POST请求中调用这个compareData函数,请求在这个承诺解析并发送响应之前超时。有什么建议吗?谢谢@Jaromanda X。这很好,但要兑现承诺需要很多时间。我在POST请求中调用这个compareData函数,请求在这个承诺解析并发送响应之前超时。有什么建议吗?