在nodejs环境使用promise函数
如果单纯的使用promise,对环境比较简单,只需要一个js文件即可。
// const p1 = new Promise((resolve, reject) => { // setTimeout(() => { // resolve('resolve') // }, 1000) // }) // const p2 = new Promise((resolve, reject) => { // setTimeout(() => { // reject('rejcet1') // }, 1000) // }) // const p3 = new Promise((resolve, reject) => { // setTimeout(() => { // reject('rejcet2') // }, 1000) // }) // const allp = [p1, p2, p3] // Promise.all(allp) // .then((res) => { // console.log(res) // }) // .catch((err) => { // console.log(err) // reject1 // }) // function verify1(content){ // return new Promise((resolve,reject)=>{ // setTimeout(function(){ // resolve(true) // },200) // }) // } // function verify2(content){ // return new Promise((resolve,reject)=>{ // setTimeout(function(){ // resolve(true) // },700) // }) // } // function verify3(content){ // return new Promise((resolve,reject)=>{ // setTimeout(function(){ // resolve(true) // },300) // }) // } // Promise.all([verify1('校验字段1的内容'),verify2('校验字段2的内容'),verify3('校验字段3的内容')]).then(result=>{ // console.log(result)//[true, true, true] // let verifyResult = result.every(item=>item) // //验证结果 // console.log(verifyResult?'通过验证':'未通过验证')// 通过验证 // }).catch(err=>{ // console.log(err) // })
如果是复杂调用(调用项目中的其他文件,且用的process.env.Env等),则启动时必须在根目录下,否则找不到变量。
cd $Root
node ./path/to/test_promise.js
import { RpcClient } from "../../indexer/rpc_client.js"; import { getValidPayload } from "../../indexer/updateSrc20.js"; const rpc_client = new RpcClient() console.log('rpc_client', rpc_client) const txhashs = [ "3212c8c1caecf1c37ea67d565d39436cc7f69d98bda3877e1e4cec1381f9aba4", "ec07c26ddecfd00d765e4c68dcd3e864d40feb86c320ad2656aff8a9f4be2c5c", "8e24e4071fe9fae6b91c0c1b964a3f3a095ccffea3406ff7df53bd790b61f1a9", ] // function generateReqFn(txhashs) { // const arr = [] // for (let txhash of txhashs) { // arr.push(new Promise(async (resolve) => { // const txInfo = await rpc_client.getTransaction(txhash) // // remove condition: !txInfo.blockhash // if (!txInfo || Object.keys(txInfo).length === 0) { // resolve(''); // } // // after block height 796000 // const payload = await getValidPayload(txInfo, 796000) // if (payload) { // resolve({ // content: payload.raw, // from: payload.sender, // to: payload.creator, // txHash: payload.tx_hash // }); // } // resolve(''); // })) // } // return arr // } function generateReqFn1() { return new Promise(async (resolve) => { // const txInfo = await rpc_client.getTransaction(txhashs[0]) // // remove condition: !txInfo.blockhash // if (!txInfo || Object.keys(txInfo).length === 0) { // resolve(''); // } // // after block height 796000 // const payload = await getValidPayload(txInfo, 796000) // if (payload) { // resolve({ // content: payload.raw, // from: payload.sender, // to: payload.creator, // txHash: payload.tx_hash // }); // } resolve(''); }) } function generateReqFn2() { return new Promise(async (resolve) => { // const txInfo = await rpc_client.getTransaction(txhashs[1]) // // remove condition: !txInfo.blockhash // if (!txInfo || Object.keys(txInfo).length === 0) { // resolve(''); // } // // after block height 796000 // const payload = await getValidPayload(txInfo, 796000) // if (payload) { // resolve({ // content: payload.raw, // from: payload.sender, // to: payload.creator, // txHash: payload.tx_hash // }); // } resolve(''); }) } Promise.all([generateReqFn1(), generateReqFn2()]).then((resArr)=>{ console.log('返回值数组', resArr); // res 接收的是一个数组,.all()方法中请求几个方法,数组的值就有几个 // res[0] 是this.getMethodsFirst()的返回成功的值 , res[1] 是this.getMethodsSecond()的返回成功的值 // 接收到返回值之后,就可以做自己想要做的事情了 }).catch(error => { console.log(error) // rejectReason of any first rejected promise });
问题终于解决了。Promise.all的第一个参数,数组的组织问题。
import assert from 'assert'; import { RpcClient } from "../indexer/rpc_client.js"; import { getValidPayload } from "../indexer/updateSrc20.js"; describe('test promise basic', function () { it('test promise example1', async function () { function verify1(content){ return new Promise((resolve,reject)=>{ setTimeout(function(){ resolve(true) },200) }) } function verify2(content){ return new Promise((resolve,reject)=>{ setTimeout(function(){ resolve(true) },700) }) } function verify3(content){ return new Promise((resolve,reject)=>{ setTimeout(function(){ resolve(true) },300) }) } await Promise.all([verify1('校验字段1的内容'),verify2('校验字段2的内容'),verify3('校验字段3的内容')]).then(result=>{ console.log(result)//[true, true, true] let verifyResult = result.every(item=>item) //验证结果 console.log(verifyResult?'通过验证':'未通过验证')// 通过验证 }).catch(err=>{ console.log(err) }) console.log('-----------'); }); it('test promise example2', async function () { const rpc_client = new RpcClient() const txhashs = [ "3212c8c1caecf1c37ea67d565d39436cc7f69d98bda3877e1e4cec1381f9aba4", "ec07c26ddecfd00d765e4c68dcd3e864d40feb86c320ad2656aff8a9f4be2c5c", "8e24e4071fe9fae6b91c0c1b964a3f3a095ccffea3406ff7df53bd790b61f1a9", ] async function generateReqFn(txhash) { return new Promise(async (resolve) => { // console.log('resolve', resolve); const txInfo = await rpc_client.getTransaction(txhash) // console.log('txInfo', txInfo.txid); if (!txInfo || Object.keys(txInfo).length === 0) { resolve(''); } const payload = await getValidPayload(txInfo, 796000) if (payload) { resolve({ content: payload.raw, from: payload.sender, to: payload.creator, txHash: payload.tx_hash }); } resolve(''); }) } // const finalArr = txhashs.map((item) => { // console.log('item', item) // return generateReqFn(item) // }) // for (let txhash of txhashs) { // arr.push() // } // console.log(Array.isArray(arr), arr) // const finalArr = generateReqFn() // console.log(typeof finalArr, finalArr) // await Promise.all([await generateReqFn(txhashs[0]), await generateReqFn(txhashs[1])]).then((resArr)=>{ await Promise.all(txhashs.map(item => generateReqFn(item))).then((resArr)=>{ console.log('返回值数组', resArr); // res 接收的是一个数组,.all()方法中请求几个方法,数组的值就有几个 // res[0] 是this.getMethodsFirst()的返回成功的值 , res[1] 是this.getMethodsSecond()的返回成功的值 // 接收到返回值之后,就可以做自己想要做的事情了 }).catch(error => { console.log(error) // rejectReason of any first rejected promise }); console.log('-----------'); }); });