📜  Node.js 处理 multipleResolves 事件

📅  最后修改于: 2022-05-13 01:56:52.481000             🧑  作者: Mango

Node.js 处理 multipleResolves 事件

'multipleResolves' 是 process 模块中的类 Process 事件,只要 Promise 出现,就会发出:

  • 解决了不止一次。
  • 不止一次被拒绝。
  • 解决后拒绝。
  • 拒绝后解决。

句法:

Event: 'multipleResolves'

参数:此事件不接受任何参数作为参数。

返回值:此事件只返回一个回调函数以供进一步操作。

示例 1:

index.js
// Node.js program to demonstrate the  
// Process 'multipleResolves' Event
  
// Importing process module
const process = require('process');
  
// Independent Block which will execute
setTimeout(() => {
   console.log('\n')
   console.log('Greetings from GeeksforGeeks');
}, 1000);
  
// Event 'multipleResolves' 
process.on('multipleResolves', (type, promise, reason) => {
  
   // Displaying the error 
   console.log("Type: ", type);
   console.log("Promsie: ", promise);
   console.log("Reason: ", reason);
});
  
const myFunction = async () => {
   const data = await new Promise((resolve, reject) => {
  
      // Calling reject after multiple resolve
      resolve('Resolve Call One');
      resolve('Resolve Call Two');
      resolve('Resolve Call Three');
      reject(new Error('Reject Error Called'));
   });
   return data
}
  
// Calling our function
myFunction().then();


index.js
// Node.js program to demonstrate the  
// Process 'multipleResolves' Event
  
// Importing process module
const process = require('process');
  
// Event 'multipleResolves' 
process.on('multipleResolves', (type, promise, reason) => {
  
   // Displaying the error 
   console.log("Type: ", type);
   console.log("Promsie: ", promise);
   console.log("Reason: ", reason);
});
  
const myFunction = async () => {
   const data = await new Promise((resolve, reject) => {
  
      // Calling reject after resolve
      resolve('Single Resolve call');
      reject(new Error('Custom Reason'));
   });
   return data
}
  
// Calling our function
myFunction().then();


使用以下命令运行index.js文件:

node index.js

输出:

示例 2:

index.js

// Node.js program to demonstrate the  
// Process 'multipleResolves' Event
  
// Importing process module
const process = require('process');
  
// Event 'multipleResolves' 
process.on('multipleResolves', (type, promise, reason) => {
  
   // Displaying the error 
   console.log("Type: ", type);
   console.log("Promsie: ", promise);
   console.log("Reason: ", reason);
});
  
const myFunction = async () => {
   const data = await new Promise((resolve, reject) => {
  
      // Calling reject after resolve
      resolve('Single Resolve call');
      reject(new Error('Custom Reason'));
   });
   return data
}
  
// Calling our function
myFunction().then();

使用以下命令运行index.js文件:

node index.js

输出:

参考: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_multipleresolves