如何避免嵌套承诺?

如何修改以下代码以避免嵌套Promises?

需要在Firestore中插入请求承诺的响应。

我还想知道当Firestore Promise解决后,如何将jsonresponse可用以将response.status发送给调用方应用程序。

const functions = require('firebase-functions');
const rp = require('request-promise')
var admin = require("firebase-admin");

var serviceaccount = require("./service_key.json");

admin.initializeApp({
   credential: admin.credential.cert(serviceaccount),databaseURL: "https://melitest-5bc38.firebaseio.com"
});

let db = admin.firestore()

exports.customHttpRequest = functions.https.onRequest((request,response) => { 

const url = 'https://jsonplaceholder.typicode.com/users'

var options = {
    uri: url,method: "GET",json: true
};

rp(options).then((jsonresponse) => {
     for(var i = 0 ; i < jsonresponse.length; i++){
        var obj = jsonresponse[i]
        var docid = obj.id

        // Warning: Avoid nesting promises.eslint(promise/no-nesting)
        db.collection("scrapeusertest").doc(String(docid)).set(obj).then(() =>{ 
            console.log(`Data was upload to firestore and the response was: ${jsonresponse}`)
            response.status(200).send(jsonresponse);
        }).catch(error =>{
            console.log(`Error uploading data Firebase: ${error}`)
        });

    }
    return console.log("Data was send")
})
.catch((err) => {
    console.log('Error:',err)

});
    return null;
});
qjjjjwqvcrrxx 回答:如何避免嵌套承诺?

最简单的选择是使用异步功能:

const db = admin.firestore()

exports.customHttpRequest = functions.https.onRequest(async (request,response) => { 

  const url = 'https://jsonplaceholder.typicode.com/users'
  const options = {
    uri: url,method: "GET",json: true
  };

  const jsonresponse = await rp(options);

  await Promise.all(jsonresponse.map(async obj => {
    const docid = obj.id
    try {
      await db.collection("scrapeusertest").doc(String(docid)).set(obj);
    } catch (error) {
      console.log(`Error uploading data Firebase: ${error}`);
    }
  }));

  console.log(`Data was upload to firestore and the response was: ${jsonresponse}`);
  response.status(200).send(jsonresponse);
});
,

使用诺言并将诺言全部用作此形状

    const res= await rp(options);
//should be soure the res is array
     await Promise.all(res.map( async item =>{
    const id=item.id;
     try {
          await db.collection("scrapeusertest").doc(String(id)).set(item);
        } catch (error) {
    //what action when handle wrror
        }))})

您可以根据需要使用res

本文链接:https://www.f2er.com/2657670.html

大家都在问