npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nested-asynchronous-requests

v0.0.1

Published

更优雅的异步嵌套处理方式和错误捕获行为。

Downloads

3

Readme

摘要

更优雅的异步嵌套处理方式和错误捕获行为。

模拟异步

在这里我们称requestAuthorrequestPricerequestPress为请求函数。且interface用于模拟某次请求的成功与否

// 标识每次请求的成功与否
const interface = [true, false, false]

const user = '张三'
const requestAuthor = () => new Promise((res, rej) => {
    setTimeout(() => {
        if (interface[0]) return res(`这个人叫${user}。`)
        rej(`请求用户${user}`)
    }, 1000)
})
const requestAge = () => new Promise((res, rej) => {
    setTimeout(() => {
        if (interface[1]) return res(`${user}的年龄`)
        rej(`请求${user}》的年龄时出错`)
    }, 1000)
})
const requestAddress = () => new Promise((res, rej) => {
    setTimeout(() => {
        if (interface[2]) return res(`${user}的住址在青岛`)
        rej(`请求${book}的住址时出错`)
    }, 1000)
})

Promise

requestAuthor()
    .then(data => {
        console.log('第一次请求', data)
        return requestAge()
    })
    .then(data => {
        console.log('第二次请求', data)
        return requestAddress()
    })
    .then(data => {
        console.log('第三次请求', data)
    })
    .catch(e => console.log('请求出错', e))

async的实现方式与上述代码大致相同,所以不再给出

使用链式then的方式,在我看来,有以下问题

  • 如果想在第三次请求中得到前面两次的请求结果,可能需要对每个then的返回值以及请求函数进行包装,或使用额外的环境进行存储
  • 如果想让某个请求函数在出错时,继续往下执行,这可能就需要对Promise作一番处理
  • 现在只是三次嵌套请求,如果继续增加则会导致then也继续增加

综上所述,现在给出nested-asynchronous-requests的解决方案

nested-asynchronous-requests

安装

npm install nested-asynchronous-requests

入门

import nestedAsynchronousRequests from 'nested-asynchronous-requests'

const asyncQueue = [requestAuthor, requestAge, requestAddress]
const over = data => console.log(data)

nestedAsynchronousRequests(asyncQueue, { over })

参数说明

接收两个参数

  • awaits:异步任务队列
  • configs:配置项

awaits

awaits必须是一个数组,该数组中的每位成员必须是函数或对象,举例

const asyncQueue = [ requestAuthor ]
const over = data => console.log(data)

nestedAsynchronousRequests(asyncQueue, { over })

awaits是对象时,格式如下

const asyncQueue = [
    requestAuthor,
    {
        func: requestPrice,
        args: ['鲨鱼辣椒'],
        callback: Function.prototype
    }
]
const over = data => console.log(data)

nestedAsynchronousRequests(asyncQueue, { over })

func为要执行的请求函数

[args]表示当执行请求函数时要传递的参数;可选

[callback]会在请求函数执行完毕时调用;可选

configs

传入nestedAsynchronousRequests的配置项,如不传入,则全部使用默认配置项

配置项

over

over: (data) => console.log(data)

必须指定该值为函数,所有请求完成后会执行该函数,此回调函数会收到最终的请求结果

forever

遇到错误时,是否继续执行(发出请求)

forever: false

single

后一个请求函数是否接收前一个请求函数的结果

whole

后一个请求函数是否接收前面所有请求函数的结果

wholetrue时,single无效,反之有效

pipes: {
    single: false,
    whole: true
}

返回值

需要注意的是,nested-asynchronous-requests不会抛出任何错误(除非你传递的参数不正确)

请求结果的返回值

请求成功

当所有请求函数都执行成功时,收到的结果如下

// 标识每次请求的失败与否
const interface = [true, true, true]
{
    "result": [
        { "flag": true, "data": { "msg": "xxxxxxxxxxx" } },
        { "flag": true, "data": { "msg": "xxxxxxxxxxxxx" } },
        { "flag": true, "data": { "msg": "xxxxxxxxxxxxxxx" } }
    ],
    "error": null
}

errornull,代表本次没有请求函数出现失败

result中存储着每次请求到的数据,flag标识当前请求是否成功,data.msg则为请求到的数据

某个请求函数失败

// 标识每次请求的失败与否
const interface = [true, false, true]
{
    "result": [
        { "flag": true, "data": { "msg": "xxxxxxxx } }
    ],
    "error": {
        "msg": "xxxxxxxxxx",
        "funcName": "requestAge"
    }
}

当某个请求失败时,error中将包含该请求函数的失败原因名字

注意

请求结果({result: ..., error: ...})的返回形式,及如何返回,会受到配置项的影响