簡體   English   中英

如何使用Promises在Node中編寫同步函數

[英]How to write a Synchronous function in Node using Promises

1.如何在Node中同步編寫Promises,以便獲得所需的輸出。 我是新手,不勝感激。

// 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.*/

bluebird請求承諾

var Promise = require('bluebird');
var request = require('request-promise');

var compareData = function(userIdArray) {
    //Promise.all(): 
        //takes an array of promises (and/or values), 
        //returns a promise of the resolved array
    return Promise.all( 
        userIdArray.map(function(id){
            return request({
                method: 'POST',
                url: 'http://localhost:6006/test1',
                headers: { 'content-type': 'application/json' },
                body: { email: id },
                json: true
            });
        }) 
    );
}

有什么需要進一步解釋的嗎?

如果您不想按照@Thomas答案使用外部庫,則可以直接使用本機Promises-並不會太冗長

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

沒有庫,並且假設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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM