[javascript] How to pass parameter to a promise function

this might seem a silly question but I am a newbie in this topic. I am working on promises on node js. And I want to pass parameter to a promise function. However I could not figure it out.

someModule.someFunction.then(username, password,function(uid) {
  /*stuff */
}

and the function is something like

var someFunction = new Promise(username, password, function(resolve, reject) {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
});

The answer is


Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

Another way(Must Try):

_x000D_
_x000D_
var promise1 = new Promise(function(resolve, reject) {_x000D_
  resolve('Success!');_x000D_
});_x000D_
var extraData = 'ImExtraData';_x000D_
promise1.then(function(value) {_x000D_
  console.log(value, extraData);_x000D_
  // expected output: "Success!" "ImExtraData"_x000D_
}, extraData);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to promise

Axios handling errors typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here Syntax for async arrow function Angular 2: How to call a function after get a response from subscribe http.post How to use fetch in typescript Returning Promises from Vuex actions Use async await with Array.map Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai using setTimeout on promise chain Why is my asynchronous function returning Promise { <pending> } instead of a value?

Examples related to parameter-passing

How to pass parameter to a promise function Check number of arguments passed to a Bash script How to pass event as argument to an inline event handler in JavaScript? Passing Parameters JavaFX FXML Invoke a second script with arguments from a script How can I pass a member function where a free function is expected? Passing variables, creating instances, self, The mechanics and usage of classes: need explanation In Javascript/jQuery what does (e) mean? How to write a bash script that takes optional input arguments? Passing Objects By Reference or Value in C#

Examples related to es6-promise

How to reject in async/await syntax? What is difference between Axios and Fetch? What is an unhandled promise rejection? JavaScript ES6 promise for loop Returning Promises from Vuex actions how to cancel/abort ajax request in axios Axios get access to response header fields How to pass parameter to a promise function Wait until all promises complete even if some rejected Handling errors in Promise.all