溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

怎么在javascript中避免回調(diào)地獄

發(fā)布時(shí)間:2021-06-02 15:58:45 來(lái)源:億速云 閱讀:203 作者:Leah 欄目:編程語(yǔ)言

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)怎么在javascript中避免回調(diào)地獄,文章內(nèi)容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

1、async.series()

當(dāng)要運(yùn)行一個(gè)函數(shù)然后在所有函數(shù)成功執(zhí)行后需要獲取結(jié)果時(shí),它很有用。  async.waterfall() 和 async.series() 之間的主要區(qū)別在于, async.series() 不會(huì)將數(shù)據(jù)從一個(gè)函數(shù)傳遞到另一個(gè)函數(shù)。

async.series([
    function(callback) {
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback) {
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results) {
    // results is now equal to ['one', 'two']
});

2、async.waterfall()

當(dāng)要一個(gè)接一個(gè)地運(yùn)行某些任務(wù),然后將結(jié)果從上一個(gè)任務(wù)傳到下一個(gè)任務(wù)時(shí),這個(gè)函數(shù)非常有用。它需要一個(gè)函數(shù)“任務(wù)”數(shù)組和一個(gè)最終的“回調(diào)”函數(shù),它會(huì)在“任務(wù)”數(shù)組中所有的函數(shù)完成后,或者用錯(cuò)誤對(duì)象調(diào)用“回調(diào)”之后被調(diào)用。

var async = require('async');
async.waterfall([
    function(callback) {
      /*  
        Here, the first argument value is null, it indicates that
        the next function will be executed from the array of functions.
        If the value was true or any string then final callback function
        will be executed, other remaining functions in the array
        will not be executed.
      */
        callback(null, 'one', 'two');
    },
    function(param1, param2, callback) {
        // param1 now equals 'one' and param2 now equals 'two'
        callback(null, 'three');
    },
    function(param1, callback) {
        // param1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    /*
      This is the final callback function.
      result now equals 'done'
    */
});

上述就是小編為大家分享的怎么在javascript中避免回調(diào)地獄了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI