簡體   English   中英

如何僅使用 async/await 語法重寫 axios promise 模塊?

[英]How can i rewrite the axios promise module with only async/await syntax?

如何僅使用 async/await 語法重寫 Axios promise 模塊? 請我是 Axios 和 promise 的新手,異步語法 => 我應該在.push() 中放什么?

const axios = require("axios");
const _ = require("lodash");
const queue = require("queue");

// To control the request rate
const GetDataQueue_B = queue({ autostart: true, concur: 1 });
// someone's codes
const getDATA = () => {
    return new Promise((resolve, reject) => {
      // To make sure only one request call
      GetDataQueue_B.push(
        async () => {
            try{
            const res = await axios.get(`${whichAPI}/api`);
            resolve(
                _.map(
                _.get(res, "data.infor"), 
                    obj => ({
                        quotes:obj.quotes,
                        author:boj.author,
                    })
                )
            );
            }catch(e) {reject(e);console.log(e);}
        }
      );
    }); 

下面是我的嘗試: => 我應該在.push() 中放什么?

const getDATA_1 = async () => {
    try{
    const res = await axios.get(`${whichAPI}/api`);
    const data =  _.map(
                    _.get(res, "data.infor"), 
                        obj => ({
                            quotes:obj.quotes,
                            author:boj.author,
                        })
                    )                 
    GetDataQueue_B.push(); // => what should i put inside the .push() method?
    return data;
    }catch(e){console.log(e);}
  };

queue在這里不是干凈代碼的最佳選擇,因為雖然它允許推送返回 promise 的函數,但它本身不會返回 promise。

我建議改用p-limit 它是這樣工作的:

const pLimit = require("p-limit");

const myQueue = pLimit(5); // Allow only 5 things running in parallel

const promise = myQueue(async () => { /* stuff */ });
// promise will resolve once the passed function ran, and will return its
// result.

因此,代碼如下所示:

const axios = require("axios");
const _ = require("lodash");
const pLimit = require("p-limit");

// To control the request rate
const GetDataQueue_B = pLimit(1);
// someone's codes
const getDATA = () => GetDataQueue_B(async () => {
  const res = await axios.get(`${whichAPI}/api`);
  return _.map(
    _.get(res, "data.infor"), 
      obj => ({
        quotes: obj.quotes,
        author: boj.author,
      })
    )
  );
}); 

我刪除了try / catch ,因為它並沒有真正做任何事情——這里的錯誤無論如何都會拒絕生成的 promise。

暫無
暫無

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

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