Home > OS >  function, that returns Promise
function, that returns Promise

Time:06-18

I have a task with a promise and I don't understand how to do it.please help

1.Imports function "func1" from file "script1.js";

const func1 = a => {
    switch (a) {
        case 'a':
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('result1');
                }, 100);
            });
        case 'b':
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('result2');
                }, 100);
            });
        default:
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('result3');
                }, 100);
            });
    };
};

module.exports = func1;
  1. Reads a string from the "input.txt"; input a

  2. Calls "func1" with an argument equal to the string;

  3. Waits until the received Promise has state: "fulfilled" and then outputs the result to the file "output.txt".

this is how i try to solve but nothing works:

const fs = require('fs')
const func1 =require ("./script1 (1)")

fs.readFile('./input.txt', 'utf8' , (err, data) => {
    if (err) {
      console.error(err)
      return
    }
        console.log(data)

        async function one (data) {
            try {
              const result = await Promise(func1);
              console.log(result);
            } catch (err) {
              console.log(err)
            }}

        fs.writeFile("output.txt",one().toString(), function(err)
       {
         if (err)
         {
             return console.error(err);
         }
  })
})

the result must be "result1"

CodePudding user response:

To call a Promise you can use async await and try catch blocks. Once you have the asynchronous result value, you can call fs.writeFile(). Try this:

func1.js:

const func1 = a => { 
    switch (a) { 
        case 'a': return new Promise((resolve) => { 
            setTimeout(() => { resolve('result1'); }, 100); 
        }); 
        case 'b': return new Promise((resolve) => { 
            setTimeout(() => { resolve('result2'); }, 100); 
        }); 
        default: return new Promise((resolve) => { 
            setTimeout(() => { resolve('result3'); }, 100); 
        }); 
    }; 
};

module.exports = func1;

index.js:

const fs = require('fs');
const func1  = require("./demo2.js")

fs.readFile('./input.txt', 'utf8' , async (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    //console.log(data)

    try {
        const result = await func1(data);
        console.log(result);
        fs.writeFile("output.txt", result, function(err) {
            if (err){
            return console.error(err);
            }
        });
    } catch (err) {
        console.log(err)
    }
});

CodePudding user response:

the async/await way is to change const result = await Promise(func1); to const result = await func1(data); you can also use then like this const result = func1(data).then(res => res);

and a better func1 would be

const func1 = a => {
    return new Promise((resolve) => {
       setTimeout(() => {
         switch(a) { // handle cases };
      });
   });
};

module.exports = func1;

CodePudding user response:

const func1 = a => {
  return new Promise((resolve) => {
    switch (a) {
      case 'a':
        setTimeout(() => {
          resolve('result1');
        }, 100);
      case 'b':
        setTimeout(() => {
          resolve('result2');
        }, 100);
      default:
        setTimeout(() => {
          resolve('result1');
        }, 100);
  };
  })
};

module.exports = func1;
const fs = require('fs')
const func1 =require ("./script1 (1)")

fs.readFile("./input.txt", "utf8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);

  async function one(data) {
    try {
      func1(data).then(result => {
        console.log(result)
      })
    } catch (err) {
      console.log(err);
    }
  }

  fs.writeFile("output.txt", one().toString(), function (err) {
    if (err) {
      return console.error(err);
    }
  });
});
  • Related